﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.IO;
using Microsoft.Win32;

namespace LiveWriterBackupWPF
{
    public class BackupMethods
    {
        internal string _tempFolder = string.Format(@"{0}SJL\", Path.GetTempPath());
        
        private void CheckTempDir()
        {
            if (Directory.Exists(_tempFolder))
            {
                Directory.Delete(_tempFolder, true);
            }
            if (!Directory.Exists(_tempFolder))
            {
                Directory.CreateDirectory(_tempFolder);
            }
        }        

        public void BackupSettings(WLBSettings settings)
        {
            settings.Save(true);            
            CheckTempDir();
            Xml2Reg.Export(@"HKEY_CURRENT_USER\" + settings.WLBRegistryKey + @"temp\", _tempFolder + @"Settings.xml");
        }
        
        public void BackupBlogSettings()
        {
            string regKey = @"HKEY_CURRENT_USER\Software\Microsoft\Windows Live\Writer";
            Xml2Reg.Export(regKey, _tempFolder + @"BlogSettings.xml");
        }

        public void BackupBlogTemplates()
        {
            string blogtemplatespath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Windows Live Writer\blogtemplates";
            CopyFolders(blogtemplatespath, _tempFolder + @"blogtemplates");
        }

        public void BackupLinkGlossary()
        {
            string linkglossarypath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Windows Live Writer\LinkGlossary";
            CopyFolders(linkglossarypath, _tempFolder + @"LinkGlossary");
        }

        public void BackupRecentPosts()
        {
            string myweblogpostspath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\My Weblog Posts";
            CopyFolders(myweblogpostspath + @"\Recent Posts", _tempFolder + @"My Weblog Posts\Recent Posts");
        }

        public void BackupDrafts()
        {
            string myweblogpostspath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\My Weblog Posts";
            CopyFolders(myweblogpostspath + @"\Drafts", _tempFolder + @"My Weblog Posts\Drafts");
        }

        public void BackupPlugins()
        {
            List<string> pluginfolders = GetPluginFolders();
            string pluginsfolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Windows Live\Writer\Plugins";
            CopyFolders(pluginsfolder, _tempFolder + @"Plugins\Plugins");
            string legacypluginsfolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Windows Live Writer\Plugins";
            if (Directory.Exists(legacypluginsfolder))
            {
                CopyFolders(legacypluginsfolder, _tempFolder + @"Plugins\Plugins");
            }

            foreach (string plugin in pluginfolders)
            {
                CopyFolders(plugin, _tempFolder + @"Plugins\Plugins");
            }
        }

        private List<string> GetPluginFolders()
        {
            List<string> folders = new List<string>();

            string[] assemblies = { @"Software\Microsoft\Windows Live\Writer\PluginAssemblies" /*, 
                                      @"SOFTWARE\Wow6432Node\Microsoft\Windows Live\Writer\PluginAssemblies"*/};

            foreach (string ass in assemblies)
            {
                RegistryKey local = Registry.LocalMachine.OpenSubKey(ass);
                RegistryKey user = Registry.CurrentUser.OpenSubKey(ass);
                if (local != null)
                {
                    foreach (string key in local.GetValueNames())
                    {
                        string plugin = local.GetValue(key).ToString();
                        string path = Path.GetFullPath(plugin).Substring(0, plugin.IndexOf(Path.GetFileName(plugin)));
                        folders.Add(path);
                    }
                }
                if (user != null)
                {
                    foreach (string key in user.GetValueNames())
                    {
                        string plugin = user.GetValue(key).ToString();
                        string path = Path.GetFullPath(plugin).Substring(0, plugin.IndexOf(Path.GetFileName(plugin)));
                        folders.Add(path);
                    }
                }
            }
            return folders;
        }

        private static void CopyFolders(string source, string destination)
        {
            if (Directory.Exists(source))
            {
                DirectoryInfo di = new DirectoryInfo(source);
                if (!Directory.Exists(destination))
                {
                    Directory.CreateDirectory(destination);
                }
                foreach (DirectoryInfo d in di.GetDirectories())
                {
                    string newDir = Path.Combine(destination, d.Name);
                    Directory.CreateDirectory(newDir);

                    CopyFolders(d.FullName, newDir);
                }
                CopyFiles(source, destination);
            }
        }

        private static void CopyFiles(string source, string destination)
        {
            if (Directory.Exists(source))
            {
                DirectoryInfo di = new DirectoryInfo(source);
                FileInfo[] files = di.GetFiles();

                foreach (FileInfo f in files)
                {
                    f.IsReadOnly = false;
                    string sourceFile = f.FullName;
                    string destFile = Path.Combine(destination, f.Name);
                    if (!File.Exists(destFile))
                    {
                        destFile = destFile.Replace("“", "_");
                        destFile = destFile.Replace("”", "_"); // Work Item #1684 http://wlwbackup.codeplex.com/WorkItem/View.aspx?WorkItemId=1684
                        destFile = destFile.Replace("\"", "_");
                        File.Copy(sourceFile, destFile);
                    }
                }
            }
        }
    }
}
